#! /usr/bin/python

"""This program opens the standard (4-column) data format file, retrieves the first column (the raw voltage) and writes this data to a file"""
import os
import scipy.io 
from scipy import array
import sys

if len(sys.argv)==1:
    print "Run this command in a dirctory where data has been ouput from the database via view_data.py"
    print "The first argument will be the name of the created directory."
    sys.exit()

dirname = sys.argv[1]
print 'Files saved to %s' % dirname
os.system('mkdir %s'  % dirname)
files = os.listdir('.')
datafiles = []

def extract_data(filename):
    infile = open(filename,'r')
    voltage = []
    for line in infile:
        words = line.split()
        voltage.append(float(words[0]))
    infile.close()
    return voltage

outfile_names = []
for file in files:
    if file.endswith('-data'): 
        print 'Saving %s' %(file)
        outfile_name = file.replace(' ','_') + '.mat'
        save_location = os.path.join(dirname, outfile_name)
        scipy.io.savemat(save_location, {'data': extract_data(file)})
        outfile_names.append(outfile_name)

text_file_name = 'files.txt'
text_file_location = os.path.join(dirname, text_file_name)
outfile_names.sort()
with open(text_file_location, 'w') as filestxt:
    for name in outfile_names:
        filestxt.write(name + '\n')
 
